<template>
  <div>
    <el-tree
      ref="tree"
      :data="permissionData"
      :props="{label:'name'}"
      :default-expand-all="true"
      :check-strictly="true"
      :show-checkbox="true"
      node-key="id"
    />
    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="saveFn">确定</el-button>
      <el-button @click="closeFn">取消</el-button>
    </div>
  </div>
</template>

<script>
import { getPermissionListAPI } from '@/api/permission'
import { NewListToTreeData } from '@/utils/index'
import { getRoleDetailAPI, assignPermAPI } from '@/api/setting'
export default {
  props: {
    assignId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      permissionData: []
    }
  },
  //   // 监听父组件传过来id的变化,如果变化了,就再次调用接口,把对应员工权限数据回填到页面上
  //   watch: {
  //     assignId: {
  //       handler(newVal, oldVal) {
  //         console.log('新的id值', newVal)
  //         console.log('旧的id值', oldVal)
  //         this.loadPermissionByRoleId()
  //       },
  //       immediate: true
  //     }
  //   },
  mounted() {
    // 调用接口，获取所有的权限点数据
    this.loadPermissionList()
    // 调用接口，获取当前这个角色已经具备的权限
    this.loadPermissionByRoleId()
  },
  methods: {
    // 获取已经有权限,回填到数据中
    async loadPermissionByRoleId() {
      const res = await getRoleDetailAPI(this.assignId)
      console.log('已经有的权限', res)
      this.$refs.tree.setCheckedKeys(res.permIds)
    },
    async loadPermissionList() {
    // 发送请求数据,获取权限列表
      const res = await getPermissionListAPI()
      this.permissionData = NewListToTreeData(res)
    },
    closeFn() {
      // 通过父组件去关闭弹层
      this.$emit('close-dialog')
      // 关闭弹窗的时候,清空数据
      this.$refs.tree.setCheckedKeys([])
    },
    // 点击确定按钮
    async saveFn() {
      const permIds = this.$refs.tree.getCheckedKeys()
      console.log(permIds)
      await assignPermAPI({
        id: this.assignId,
        permIds
      })
      // 提示
      this.$message.success('保存角色的权限成功')
      // 调用关闭那个方法,关闭弹窗和清空数据
      this.closeFn()
    }
  }
}
</script>

<style>

</style>
